<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="/res/back/css/base.css" rel="stylesheet" type="text/css" />
<link href="/res/third/bootstrap3/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="/res/common/js/jquery.1.9.1.min.js" type="text/javascript"></script>
<script src="/res/third/easyUI/jquery.easyui.min.js" type="text/javascript"></script>
<script src="/res/third/artDialog/jquery.artDialog.js" type="text/javascript"></script>
<script src="/res/third/validate/jquery.validate.js" type="text/javascript"></script>
<script src="/res/third/laytpl/template.js" type="text/javascript"></script>

<style>
.noselect{
	background-color: rgba(99, 230, 99, 0.8);
}
.achecked{
	background-color: green;
}

</style>	
</head>
<body>
	[#if contents ?? && maxlength!=0 ]
	<div class="panel panel-info panel-content" style="overflow: auto;" >
		<div class="panel-heading"  style="position: fixed;height: 70px;width: 99%;" >
			<table>
				<tr>	
					名称: ${enquiry.title}
				</tr>
				<tr>
                    [#if !mulityAnalysis?? ]
					<td class="w80 ">
						<button type="button" class="btn  btn-success"  onclick="submodel()" >确定</button>
					</td>
                    [/#if]
			
					<td class="w80 ">
						<button type="button" class="btn  btn-info"  onclick="shownocontent()" >查看未匹配行</button>
					</td>
					<td class="w80 ">
						<button  id="mulityset"  type="button" class="btn  btn-primary " style="display: none;"   onclick="mulityset()" >批量设置系统</button>
					</td>
                    <td  class="w80 ">
                        <button  id="delLine"  type="button" class="btn  btn-danger" style="display: none;"   onclick="delLine()" >删除行</button>
                    </td>
					<td>
						[#if titlePerfect]&nbsp;&nbsp;<b id="icon_140"  class="glyphicon glyphicon-thumbs-up"></b>[/#if]
						[#if contentPerfect ]&nbsp;&nbsp;<b id="icon_140"  class="glyphicon glyphicon-thumbs-up">&nbsp;&nbsp;&nbsp;&nbsp;</b>[/#if]
					</td>
				
				</tr>
				
			</table>
		</div>
	<form id="itemform"  action="/purchase/o_saveitem2.do" method="post"   style="padding-top: 70px;"  >
		<input type="hidden" value="${enquiry.id}" name="enquiryid" id="enquiryid"  />
		<div >
		<table id="itemTable"   class="table table-hover table-bordered table-striped table-condensed">
			<thead>
				<tr>
					<th>#</th>
					<th>系统名称</th>
					[#assign  index = maxlength /]
					
					[#list 1..index  as b]
					<th class="cell_${b}">
						<select class="typename" name="typename" attnum=${b} >
						
							[#if titleindex?? && (titleindex?size > b-1) ]
									[#assign a = titleindex[b-1] ]
							[#else]									
									[#assign a = 0 ]
							[/#if ]
							
							<option  value="0"  >请选择</option>
							<option  [#if a==1] selected="selected" [/#if] value="1"  >设备名称</option>
							<option  [#if a==2] selected="selected" [/#if] value="2" >品牌</option>
							<option  [#if a==3] selected="selected" [/#if] value="3" >型号</option>
							<option  [#if a==4] selected="selected" [/#if] value="4" >单位</option>
							<option  [#if a==5] selected="selected" [/#if] value="5" >数量</option>
							<option  [#if a==6] selected="selected" [/#if] value="6" >技术参数</option>
						</select>
						
					</th>
					[/#list]
				</tr>
				<tr>
					<td>
					<span>
						全<input type="checkbox" class="checkedall"  >
					</span>
					</td>
					<td>
					<span style="font-size: 10px;color: #918C8C;" >原始名称 ：</span>
					</td>
					[#list 1..index  as a]
					<td  class="cell_${a}">
						<button  onclick="delcell(${a})" class="btn btn-xs btn-danger" >删除该列</button>
						[#--原始列名--]
						[#if titles?? && (titles?size > a-1) ]
							<span style="font-size: 10px;color: #918C8C;" >${titles[a-1]}</span>
							<input  type="hidden"   name="oldtitle"  value="${titles[a-1]}"    />
						[/#if ]
					</td>	
					[/#list]
				</tr>
			</thead>
			[#assign  index = 0 /]
				[#list contents as cc ]
					<tr attindex="${index+1}"  class="tr_${cellStats[index].rownum+1}" >
						<td>
							<label >
							<span class="spanindex" >${index+1}</span>
							<span>
								<input type="checkbox"  value="${index}"  class="checksystem"    />
							</span>
							</label>
							<input type="hidden"  name=".enquiryId" value="${enquiry.id!}"  />
						</td>

						[#list cc as c]
							[#if c_index==0]
								<td>
								<input id="system_${index}" type="button"   attshebei=[#if  md5secret?? && md5secret?size!=0 && shebeiindex!=-1 ] "${md5secret[index]}" [#else]""[/#if]    value="[#if cc[0]=="" ]选择系统[#elseif cc[0]?index_of(",")!=-1 ]有多个匹配[#else]${categorysMap[cc[0]].name!}[/#if]"  class="choosecatclass w120 btn [#if cc[0]=="" ]btn-default[#elseif cc[0]?index_of(",")!=-1  ]btn-danger[#else]btn-success[/#if]"  attchoose="${index+1}" onclick="chooseService(this)"   />
								<input class="fcateid"  type="hidden" name=".categoryPId"  value="[#if cc[0]!="" ]${cc[0]}[/#if]"  />
								<input  type="hidden" name=".categorySId"    />
								[#--无法识别的系统，需要保存到数据库--]
								<input type="hidden" name=".needrepository"   value=[#if cc[0]==""]1[#else]0[/#if]  >
								</td>
							[#else]	
								<td class="cell_${c_index}"><input   name=""    class="input_${c_index}" type="text"  value="${c!?html}" > </td>
							[/#if]
						[/#list]
						[#if cc?size-1 < maxlength]
							[#--补充空白列--]
							[#list 0..(maxlength - cc?size) as c]
								<td class="cell_${c_index + cc?size}"><input   name=""    class="input_${c_index+ cc?size}" type="text"  value="" > </td>
							[/#list]
						[/#if]
						
					</tr>
					[#assign  index = index+1 /]
				[/#list]

			
		</table>
		</div>
		</form>
	</div>
	<div style="display: none;" >
		<div id="nocontent" >
		<div style="overflow: scroll;max-height: 500px;min-width:300px;">
			[#if nocontents?? ]
				<ul>
					[#list nocontents  as nocontent]
                        <li>
							[#list nocontent  as c]
								[#if c!=""]
                                    <a  onclick="changeastat(this)"  href="javascript:void(0)" style="padding-right:10px;padding-right: 10px;" >${c!}</a>
								[/#if]
								[#if !c_has_next ]
                                    <a onclick="backtotable(this)" href="javascript:void(0)" >还原</a>
								[/#if]
							[/#list]
                        </li>
					[/#list]
				</ul>
			[#else]
				没有
			[/#if]
		</div>
		</div>
		
	</div>
	

	<script type="text/javascript">
		//设备名称，品牌 ，型号  ,单位 ,数量,技术参数
		var selectnames =["productName","brand","model","unit","quantity","descr"];
	    //切换选项，确保不重复就可
		$(".typename").on("change",function(){
			
			var  thisval = $(this).val();
			
			if(thisval!=0){//将相同的选项设置为请选择
				var hadvnum =[];
				hadvnum.push(thisval);
				
				$(".typename").each(function(i){
					var otherv = $(this).val();
					if(otherv == thisval ){
						$(this).val(0);
					}else{
						hadvnum.push(otherv);
					}
				});
				
				//没有被选择的加颜色
 				var nums = hadvnum.join("");
				$(".noselect").removeClass("noselect");
				for(var i=1;i<7;i++){
					if(nums.indexOf(i)==-1){
						$(".typename").find("option[value='"+i+"']").addClass("noselect");
					}
				} 
				
			}
			
			$(this).val(thisval);
		})





        function validBeforeSub() {
            var success = true;
            var msg ="";
            $(".typename").each(function(){
                var thisval = $(this).val();
                if(thisval==0){
                    success = false;
                    msg="失败：请确定每一列的名称";
                    return false;
                }

            })

            if(!success){
                art.dialog.tips(msg);
                return false;
            }else{
                //确定每列的name
                $(".typename").each(function(i){
                    var thisval = $(this).val();
                    var attnum = $(this).attr("attnum");
                    //拿到name值
                    var namev = selectnames[thisval-1];
                    //设置name值
                    $(".input_"+attnum).each(function(){
                        $(this).attr("name","."+namev);
                    })
                });


                $(".fcateid").each(function(){
                    var v = $(this).val();
                    if(v=="" || v.indexOf(",")!=-1){
                        success=false;
                        return false;
                    }
                })
                if(!success){
                    art.dialog.tips("必须选择系统！");
                    return false;
                }


                //验证设备名称
                $("#itemform").find("input[name$='productname']").each(function(){
                    var productname = $(this).val();
                    if(productname==""){
                        success = false;
                        return false;
                    }
                })

                if(!success){
                    art.dialog.tips("设备名称不能有空！");
                    return false;
                }

                //验证数值 ,数量必须全为数字
                $("#itemform").find("input[name$='quantity']").each(function(){
                    var num = $(this).val();
                    if(num=="" || isNaN(num) || parseFloat(num)<0 ){
                        success = false;
                        return ;
                    }
                });

                if(!success){
                    art.dialog.tips("数量对应的列必须全为数字且不能小于0!");
                    return false;
                }


                return true;
            }
        }


        function createData() {
            var items =[];
            var typenames =[];
            var oldtitles=[];
            $("#itemTable").find("tr").each(function () {
                var obj={};
                $(this).find("input[name]").each(function () {
                    var names = $(this).attr("name");
                    var inputval = $(this).val();
                    if(names.indexOf(".")!=-1){
                        var k = names.split(".")[1];
                        obj[k]=inputval;
                    }else{
                        if(names=="oldtitle"){
                            oldtitles.push(inputval);
                        }
                    }
                });
                if(!jQuery.isEmptyObject(obj)){
                    items.push(obj);
                }
            });

            $("select[name='typename']").each(function(){
                typenames.push($(this).val());
            });

            var obj={item:items,typenames:typenames,oldtitles:oldtitles,enquiryid:$("#enquiryid").val(),type:1};

            return obj;
        }

        //准备提交
		function submodel(){

            	var validTrue = validBeforeSub();

				if(!validTrue){
					return ;
				}

                var obj =   createData();


 				//设置后提交   转json提交
 				art.dialog.post({
					url:"/enquiry/o_saveitem.do",
					data:JSON.stringify(obj),
                    contentType:"application/json",
					success:function(data){
						if(data.success){
							//refresh();
							//更新原
							art.dialog.alert("操作成功",function(){
								top.closeTempTab(true);
							})
						}else{
							art.dialog.tips(data.msg);
						}
					}
				});
		}

	    function delcell(cellnum){
	    	$(".cell_"+cellnum).remove();
	    }

	    function backtotable(obj) {
            var achecked = $(obj).siblings(".achecked");
            var maxsize = $("#itemTable").find("tr").eq(0).find("th").size()-2;
            if(achecked.size()!=0){
                var tds=[];
				var attnum=[];
                var isindexx = $(obj).parent().find("a").eq(0).text();
                achecked.each(function (i) {
					if(tds.length < maxsize){
						tds.push($(this).text());
					}
                });
                if(tds.length < maxsize){
                    var lasblank = maxsize-tds.length;
                    for(var i=0;i<lasblank;i++){
                        tds.push("");
                    }
                }
                $(".typename").each(function () {
					var num = $(this).attr("attnum");
                    attnum.push(num);
                });

                var data={};
                data.tds =tds;
				data.attnum=attnum;
				data.num=isindexx;
                var html = template('trmodel', data);

				var indexnum = parseInt(isindexx);
				var maxtrsize = $("#itemTable").find("tr").size()-2;
				var xx =0;
				var num = indexnum;
				var hasfond = false;
				while (num>0){
					num--;
                    if($(".tr_"+num)[0]){
                        $(".tr_"+num).after(html);
						hasfond=true;
						break;
                    }
				}
				if(!hasfond){
					while (indexnum<maxtrsize){
						indexnum++;
                        if($(".tr_"+indexnum)[0]){
                            $(".tr_"+indexnum).before(html);
                            hasfond=true;
                            break;
                        }
					}
				}

				if(!hasfond){
					$("#itemTable").find("tr").eq(1).after(html);
				}
				resetIndex();
            }

        }


        function resetIndex(){
			$(".spanindex").each(function (i) {
				$(this).text(i+1);
            })

			$(".choosecatclass").each(function (i) {
				$(this).attr("id","system_"+i).attr("attchoose",(i+1));
            })

		}

        function changeastat(obj) {
        	if($(obj).hasClass("achecked")){
        		$(obj).removeClass("achecked");
			}else{
                $(obj).addClass("achecked");
			}
        }
	    
	    
	    var cobj;
	    var cdialog;
	    var ismulity=false;
	    //选择器
	    function chooseService(obj){
	    	ismulity=false;
            var index = $(obj).attr("attchoose");
	    	cobj=$(obj);
	    	if(cdialog){
		    	cdialog.close();
	    	}
	    	var ccv = cobj.next().val();
	    	var attname = cobj.attr("attshebei");
	    	cdialog=art.dialog.load("选择系统->序号:"+index,"/category/v_choose_category.do?curent="+ccv+"&attname="+attname);
	    }
	    
	    //选择回调
	    function chooseCallback(name, id,topid){
	    	if(!ismulity){
		    	if(name&&id){
			    	cobj.val(name);//显示名称
			    	cobj.removeClass("btn-danger").addClass("btn-success");
			    	cobj.next().val(id).next().val(topid).next().val(1);//显示值
		    	}
	    	}else{
		    	if(name&&id){
		         	$(".checksystem:checked").each(function(){
			    		var checkedval = $(this).val();
			    		$("#system_"+checkedval).val(name).addClass("btn-success").next().val(id).next().val(topid).next().val(1);
			    		$(this).attr("checked",false);
			    	});
		         	$(".checkedall")[0].checked = false;
		    	}
	    	}
	    	cdialog.close();
	    }
	    
	    $(".checksystem").each(function(){
	    	$(this).click(function(){
	    		var checkedsize = $(".checksystem:checked").size();
	    		if(checkedsize==0){
	    			$("#mulityset").hide();
                    $("#delLine").hide();
	    		}else{
	    			$("#mulityset").show();
                    $("#delLine").show();
	    		}
	    	});
	    });

        function delLine() {
            art.dialog.confirm("确认删除",function(){
                var _this = null;
                var indexnum=null;
                $(".checksystem:checked").each(function(i){
                    var trobj = $(this).parents("tr");
                    if(i==0){
                        _this = $(this);
                    }else{
                        trobj.remove();
                    }
                });

                var _parent = _this.parents("tr");
                var indexnum = parseInt(_parent.attr("attindex"));
                _parent.nextAll().each(function(){
                    $(this).attr("attindex",indexnum);
                    $(this).find("td").eq(0).find("span").eq(0).text(indexnum);
                    indexnum++;
                });
                _parent.remove();

                $("#mulityset").hide();
                $("#delLine").hide();
                art.dialog.tips("已删除");
            });

        }


	    //批量设置系统
	    function mulityset(){
	    	ismulity=true;
	     	if(cdialog){
		    	cdialog.close();
	    	}
	     	cdialog=art.dialog.load("选择系统->批量设置","/category/v_choose_category.do");
	    }
	    
	    //全选方法
	    $(".checkedall").click(function(){
	    	var setchecked = false;
	    	if($(this).is(":checked")){
	    		setchecked=true;
	    		$("#mulityset").show();
                $("#delLine").show();
	    	}else{
	    		$("#mulityset").hide();
                $("#delLine").hide();
	    	}
	    	
	    	$(".checksystem").each(function(){
				$(this)[0].checked =setchecked;
	    	})
	    });
	    
	    //展示未匹配的
	    function shownocontent(){
	    	art.dialog({
	    		title:"未匹配",
	    	    content: document.getElementById('nocontent')
	    	});
	    }
	    
	</script>
	
	[#else]
		${msg!"没有任何信息"}
	[/#if]
<script id="trmodel"   type="text/html">
    <tr  class="tr_{{num}}" >
        <td>
            <label >
                <span class="spanindex">1</span>
                <span>
					<input type="checkbox"  value=""  class="checksystem"    />
				</span>
            </label>
            <input type="hidden"  name=".enquiryId" value="${enquiry.id!}"  />
        </td>
        <td>
            <input id="system_" type="button"  value="选择系统" class="choosecatclass w120 btn btn-default" attchoose=""  onclick="chooseService(this)">
            <input class="fcateid" type="hidden" name=".categoryPId" value="" />
            <input type="hidden" name=".categorySId" />
            <input type="hidden" name=".needrepository" value="1" />
        </td>
		{{each tds as value index }}
		<td class="cell_{{attnum[index]}}">
            <input name="" class="input_{{attnum[index]}}" type="text" value="{{value}}">
		</td>
		{{/each}}
	</tr>
</script>
</body>

</html>